package com.ming.study.utils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ming.study.exceptionHandler.MingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class CookiesUtils {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public  boolean saveCookies(String id, Map<String, String> cookies) {
        String cookiesStr =  JSON.toJSON(cookies).toString();
        this.redisTemplate.opsForValue().set(id + ":cookie", cookiesStr, JwPropertiesUtil.COOKIE_TIME, TimeUnit.SECONDS);
        return true;
    }
    public Map getCookies(String id) {
        String cookiesStr = redisTemplate.opsForValue().get(id + ":cookie");
        ObjectMapper objectMapper = new ObjectMapper();
        Map cookies;
        try{
            cookies = objectMapper.readValue(cookiesStr, Map.class);
        } catch (IllegalArgumentException e) {
            throw new MingException(ResultCodeImpl.ERROR_LOGIN_OVERTIME);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MingException(ResultCodeImpl.ERROR_REDIS);
        }
        return cookies;
    }
}
